package main

import (
	"log"
	"net/http"
	"os"

	"github.com/gin-gonic/gin"
)

func main() {
	UploadFile()
}

func ping() {
	r := gin.Default()
	r.GET("/ping", func(c *gin.Context) {
		c.JSON(200, gin.H{"message": "pong"})
	})
	r.Run()
}

func path() {
	router := gin.Default()
	// 匹配 /user/zhangsan
	router.GET("/user/:name", func(c *gin.Context) {
		name := c.Param("name")
		c.String(http.StatusOK, "Hello %s", name)
	})
	router.Run()
}

func path2() {
	// http://localhost:8080/user/zhangsan/123?lastname=san
	router := gin.Default()
	router.GET("/user/:name/*action", func(c *gin.Context) {
		name := c.Param("name")
		action := c.Param("action")
		firstname := c.DefaultQuery("firstname", "zhang")
		lastname := c.Query("lastname")
		c.String(http.StatusOK, "Hello %s action:%s , firstname:%s, lastname:%s", name, action, firstname, lastname)
	})
	router.Run()
}

const (
	filepath = "dist/uploads/"
)

func UploadFile() {
	router := gin.Default()
	router.POST("/upload", func(c *gin.Context) {
		header, _ := c.FormFile("file")
		filename := header.Filename
		log.Println(filename)
		//如果没有filepath文件目录就创建一个
		CreatePathIfNoExsit(filepath)
		filedir := filepath + filename
		c.SaveUploadedFile(header, filedir)
		c.JSON(200, gin.H{"filepath": "localhost:8080/" + filedir})
		//c.String(http.StatusOK, fmt.Sprintf("'%s'upload!", filename))
	})
	router.GET("/:filename", func(c *gin.Context) {
		filename := c.Param("filename")
		c.File(filepath + filename)
	})
	router.Run(":8666")
}

func CreatePathIfNoExsit(filepath string) bool {
	if _, err := os.Stat(filepath); err != nil {
		if !os.IsExist(err) {
			os.MkdirAll(filepath, os.ModePerm)
			return true
		}
	}
	return false
}
